package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//ip 拦截 黑客ip
@Component//交由spring 容器
public class AuthorizeFilter implements GlobalFilter , Ordered {
   //权限认证
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
      //用户是登录请求  放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getURI().getPath();
        if(uri.contains("/admin/login")){
            return chain.filter(exchange);
        }
        // 访问时侯 request headers
        //请求头中获取 token
        HttpHeaders headers =  request.getHeaders();
        String jwt = headers.getFirst("token");
          //jwt 空 拒绝访问
        if(StringUtils.isEmpty(jwt)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
           return response.setComplete();
        }
        //jwt 是否合法
        try {
            JwtUtil.parseJWT(jwt);
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


    }

    //顺序，值越小，越先执行
    @Override
    public int getOrder() {
        return 0;
    }




}
